<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { addClass } from '@/api/manager.js';

const props = defineProps({
  visible: Boolean,
});

const emit = defineEmits(['update:visible']);

const localVisible = ref(props.visible);

watch(() => props.visible, (val) => {
  console.log('父组件 visible 变化:', val);
  localVisible.value = val;
});
watch(localVisible, (val) => {
  console.log('本地 visible 变化:', val);
  emit('update:visible', val);
});

const close = () => {
  console.log('关闭触发');
  localVisible.value = false;
};

const form = ref({
  className: '',
  classId: '',
  belongTo: '',
  classStatus: 1,
  courseProperty: '',
  courseName: '',
  planCourseCount: 0,
  remainCourseCount: 0,
  volume: 0,
  defaultClassroom: '',
  startTime: '',
  endTime: '',
  classTime: '',
  teacher: '',
  isCompleted: false,
});

const submit = async () => {
  console.log('提交触发，表单数据:', JSON.stringify(form.value, null, 2));
  try {
    const formData = {
      ...form.value,
      isCompleted: form.value.isCompleted ? 1 : 0, // 将布尔值转换为整数
      startTime: form.value.startTime ? new Date(form.value.startTime).toISOString().slice(0, 19) : null, // 格式化为 YYYY-MM-DDTHH:mm:ss
      endTime: form.value.endTime ? new Date(form.value.endTime).toISOString().slice(0, 19) : null,
      classTime: form.value.classTime ? new Date(form.value.classTime).toISOString().slice(0, 19) : null,
    };
    delete formData.classId; // 移除 classId，因为它可能由数据库生成
    console.log('发送的表单数据:', JSON.stringify(formData, null, 2));
    const response = await addClass(formData);
    console.log('添加班级成功:', response.data);
    ElMessage.success('班级添加成功！');
    close();
    form.value = {
      className: '',
      classId: '',
      belongTo: '',
      classStatus: 1,
      courseProperty: '',
      courseName: '',
      planCourseCount: 0,
      remainCourseCount: 0,
      volume: 0,
      defaultClassroom: '',
      startTime: '',
      endTime: '',
      classTime: '',
      teacher: '',
      isCompleted: false,
    };
  } catch (error) {
    console.error('添加班级失败:', error.response ? error.response.data : error);
    ElMessage.error('添加班级失败，请稍后重试！');
  }
};
</script>

<template>
  <transition name="ios-zoom">
    <div
        v-if="localVisible"
        class="dialog-wrapper"
        @click.self="close"
        role="dialog"
        aria-modal="true"
    >
      <div class="dialog-box">
        <h2>新增班级</h2>
        <div class="dialog-body">
          <form @submit.prevent="submit">
            <!-- 班级信息 -->
            <section class="form-group">
              <h3>班级信息</h3>
              <div class="row">
                <label>
                  班级名称
                  <input v-model="form.className" type="text" required/>
                </label>
                <label>
                  班级ID
                  <input v-model="form.classId" type="text" disabled/>
                </label>
              </div>
              <div class="row">
                <label>
                  所属校区
                  <input v-model="form.belongTo" type="text"/>
                </label>
                <label>
                  班级状态
                  <select v-model="form.classStatus">
                    <option :value="1">正常</option>
                    <option :value="0">停用</option>
                  </select>
                </label>
              </div>
              <label>
                课程属性
                <input v-model="form.courseProperty" type="text"/>
              </label>
            </section>

            <!-- 课程信息 -->
            <section class="form-group">
              <h3>课程信息</h3>
              <div class="row">
                <label>
                  课程名称
                  <input v-model="form.courseName" type="text"/>
                </label>
                <label>
                  计划课时数
                  <input v-model.number="form.planCourseCount" type="number" min="0"/>
                </label>
              </div>
              <div class="row">
                <label>
                  剩余课时数
                  <input v-model.number="form.remainCourseCount" type="number" min="0"/>
                </label>
                <label>
                  容量
                  <input v-model.number="form.volume" type="number" min="0"/>
                </label>
              </div>
              <label>
                默认教室
                <input v-model="form.defaultClassroom" type="text"/>
              </label>
            </section>

            <!-- 时间信息 -->
            <section class="form-group">
              <h3>时间信息</h3>
              <div class="row">
                <label>
                  开班时间
                  <input v-model="form.startTime" type="datetime-local"/>
                </label>
                <label>
                  结班时间
                  <input v-model="form.endTime" type="datetime-local"/>
                </label>
              </div>
              <label>
                课堂时间
                <input v-model="form.classTime" type="datetime-local"/>
              </label>
            </section>

            <!-- 教师信息 -->
            <section class="form-group">
              <h3>教师信息</h3>
              <label>
                讲师
                <input v-model="form.teacher" type="text"/>
              </label>
              <label class="checkbox-label">
                <input type="checkbox" v-model="form.isCompleted"/>
                是否完成
              </label>
            </section>

            <div class="footer">
              <button type="button" @click="close">取消</button>
              <button type="submit">确认添加</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </transition>
</template>

<style scoped>
/* 与提供的样式相同 */
.dialog-wrapper {
  position: fixed;
  inset: 0;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  z-index: 9999;
  overflow-y: auto;
}

.dialog-box {
  background: #fff;
  border-radius: 20px;
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  transform-origin: center center;
  display: flex;
  flex-direction: column;
}

h2 {
  margin: 24px 24px 0;
  text-align: center;
  font-weight: 700;
  font-size: 24px;
}

.dialog-body {
  overflow-y: auto;
  padding: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-group h3 {
  font-size: 18px;
  margin-bottom: 12px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 4px;
  font-weight: 600;
}

.row {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

label {
  flex: 1;
  font-weight: 500;
  font-size: 14px;
  display: flex;
  flex-direction: column;
}

input[type="text"],
input[type="number"],
input[type="datetime-local"],
select {
  margin-top: 6px;
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid #ccc;
  font-size: 14px;
  box-sizing: border-box;
}

.checkbox-label {
  flex-direction: row;
  align-items: center;
  gap: 8px;
  margin-top: 12px;
  font-weight: 500;
  user-select: none;
}

.footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #eee;
  margin-top: auto;
}

button {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #66b1ff;
}

button[type='button'] {
  background-color: #999;
}

button[type='button']:hover {
  background-color: #bbb;
}

.ios-zoom-enter-active,
.ios-zoom-leave-active {
  transition: opacity 0.35s ease, transform 0.35s cubic-bezier(0.22, 1.2, 0.36, 1.2);
}

.ios-zoom-enter-from,
.ios-zoom-leave-to {
  opacity: 0;
  transform: scale(0.8);
}

.ios-zoom-enter-to,
.ios-zoom-leave-from {
  opacity: 1;
  transform: scale(1);
}
</style>